import React, { Component } from 'react';
import ReactDOM from 'react-dom';

class Text extends Component {
  constructor(props) {
    super(props);
    this.divRef = React.createRef();
  }

  componentDidMount() {
    if (this.divRef.current) {
      this.domNode = ReactDOM.findDOMNode(this.divRef.current);
    }
  }

  getText() {
    if (this.domNode) {
      return this.domNode.textContent;
    }
    return '';
  }

  onChange = value => {
    const { editor, node } = this.props;
    const data = node.data.set('text', value);
    editor.updateNode(node, { data });
  };

  onBlur = () => {
    const text = this.getText();
    this.onChange(text);
  };

  render() {
    const { getData, getStyle } = this.props;
    const style = getStyle();
    const { fontStyle, ...rest } = style;
    let fontStyleObj = null;
    switch (fontStyle) {
      case 'bold':
        fontStyleObj = { fontWeight: 'bold' };
        break;
      case 'italic':
        fontStyleObj = { fontStyle: 'italic' };
        break;
      case 'underline':
        fontStyleObj = { textDecoration: 'underline' };
        break;
      default:
        break;
    }

    return (
      <div
        ref={this.divRef}
        style={{ ...rest, ...fontStyleObj, minWidth: "10px", minHeight: "10px" }}
        onChange={this.onChange}
        onBlur={this.onBlur}
        suppressContentEditableWarning
        // contentEditable
      >
        {getData('text')}
      </div>
    );
  }
}

export default Text;
